package com.easy.config;

import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName MyAutoConfigurationRegister
 * @Description TODO
 * @Author zheng
 * @Date 2022/3/29 10:42
 * @Version 1.0
 **/
public class MyAutoConfigurationRegister implements BeanClassLoaderAware, ImportBeanDefinitionRegistrar {
    private ClassLoader classLoader;

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        List<String> list = SpringFactoriesLoader.loadFactoryNames(MyAutoConfiguration.class, classLoader);
        if (list.isEmpty()) {
            System.out.println("未加载到数据");
            return;
        }
        list.forEach(className -> {
            try {
                Class<?> aClass = classLoader.loadClass(className);
                String simpleName = aClass.getSimpleName();
                AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(className).getBeanDefinition();
                registry.registerBeanDefinition(simpleName, beanDefinition);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        });
        System.out.println(Arrays.toString(list.toArray()));
    }
}
